package com.qys.livesMall.common.exception;

import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MessageUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;


/**
 * 描述: 全局错误统一处理控制中心
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 生产环境
     */
    private final static String ENV_PROD = "prod";

    /**
     * 当前环境
     */
    @Value("${spring.profiles.active}")
    private String profile;

    @Resource
    private MessageSource messageSource;

    @ExceptionHandler(QysException.class)
    public R businessException(QysException qysException) {
        log.error(ExceptionUtil.getMessage(qysException));
        return R.fail(qysException.getCode(), qysException.getMessage());
    }




    /**
     * Controller上一层相关异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = {
//            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    public R<Void> handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        int code = ExceptionEnum.INTERNAL_SERVER_ERROR.getCode();

        if (ENV_PROD.equals(profile)) {
            // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如404.
            code = ExceptionEnum.UNKNOWN.getCode();
            QysException QysException = new QysException(ExceptionEnum.UNKNOWN);
            String message = getMessage(QysException);
            return R.fail(code, message);
        }

        return R.fail(code, e.getMessage());
    }


    /**
     * 参数绑定异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = BindException.class)
    public R<Void> handleBindException(BindException e) {
        log.error("参数绑定校验异常", e);

        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 参数校验异常，将校验失败的所有异常组合成一条错误信息
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Void> handleValidException(MethodArgumentNotValidException e) {
        log.error("参数绑定校验异常", e);

        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 包装绑定异常结果
     *
     * @param bindingResult 绑定结果
     * @return 异常结果
     */
    private R<Void> wrapperBindingResult(BindingResult bindingResult) {
        StringBuilder msg = new StringBuilder();

        for (ObjectError error : bindingResult.getAllErrors()) {
            msg.append(", ");
//            if (error instanceof FieldError) {
//                msg.append(((FieldError) error).getField()).append(": ");
//            }
            msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
            break;
        }

        String message=null;
        try {
            MessageUtils.message(msg.substring(2));
        }catch (Exception e){
            message=msg.substring(2);
        }
        return R.fail(ExceptionEnum.BAD_REQUEST.getCode(), message);
    }

    /**
     * 未定义异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e) {
        log.error(e.getMessage(), e);

        if (ENV_PROD.equals(profile)) {
            // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
            int code = ExceptionEnum.INTERNAL_SERVER_ERROR.getCode();
            QysException QysException = new QysException(ExceptionEnum.INTERNAL_SERVER_ERROR);
            String message = getMessage(QysException);
            return R.fail(code, message);
        }

        return R.fail(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
    }

        /**
     * 获取国际化消息
     * 这里可以做处理
     *
     * @param e 异常
     */
    public String getMessage(QysException e) {
        String code = "response." + e.getCode();
        String message = messageSource.getMessage(code, null, LocaleContextHolder.getLocale());

        if (message.isEmpty()) {
            return e.getMessage();
        }

        return message;
    }
}
